/* eslint-disable react-hooks/exhaustive-deps */
import { LockOutlined, SafetyOutlined, UserOutlined } from '@ant-design/icons';
import { Alert, message, Input } from 'antd';
import React, { useState, useEffect, memo } from 'react';
import { ProFormCaptcha, ProFormCheckbox, ProFormText, LoginForm } from '@ant-design/pro-form';
import { useIntl, history, FormattedMessage, useModel } from 'umi';
import Footer from '@/components/Footer';
import { Scene, PointLayer, LineLayer } from '@antv/l7';
import { GaodeMap } from '@antv/l7-maps';
import { useRequest } from 'ahooks';
import { doFetch, getFetch } from '@/utils/doFetch';
import drawAuthCode from '@/utils/draw';
import styles from './index.less';
import { encode_utf8_b64, decode_utf8_b64 } from '@/utils/encode';

const MapBg = memo(() => {
  useEffect(() => {
    let scene = new Scene({
      id: 'map',
      antialias: true,
      logoVisible: false,
      map: new GaodeMap({
        pitch: 64.88,
        style: 'dark',
        center: [114.026288, 22.53684],
        zoom: 13,
        showLabel: false,
        minZoom: 6,
      }),
    });
    scene.on('loaded', () => {
      fetch(
        'https://gw.alipayobjects.com/os/basement_prod/513add53-dcb2-4295-8860-9e7aa5236699.json',
      )
        .then((res) => res.json())
        .then((data) => {
          const pointLayer = new PointLayer({})
            .source(data)
            .size(1)
            .color('h8', [
              '#096ad3',
              '#1558AC',
              '#096ad3',
              '#4D89E5',
              '#64A5D3',
              '#72BED6',
              '#096ad3',
              '#A6E1E0',
              '#B8EFE2',
              '#D7F9F0',
            ])
            .style({
              opacity: 1,
            });

          fetch('https://gw.alipayobjects.com/os/rmsportal/UEXQMifxtkQlYfChpPwT.txt')
            .then((res) => res.text())
            .then((datas) => {
              const layer = new LineLayer({
                blend: 'normal',
              })
                .source(datas, {
                  parser: {
                    type: 'csv',
                    x: 'lng1',
                    y: 'lat1',
                    x1: 'lng2',
                    y1: 'lat2',
                  },
                })
                .size(1)
                .shape('arc3d')
                .color('#1890ff')
                .animate({
                  enable: true,
                  interval: 0.1,
                  trailLength: 0.5,
                  duration: 2,
                })
                .style({
                  opacity: 0.8,
                });
              scene.addLayer(layer);
              scene.addLayer(pointLayer);
            });
        });
    });
  });
  return <div id="map" style={{ width: '100vw', height: '100vh' }} />;
});
var Letter = 'ABCDEFGHIJKLMNOPQRSTUVWHYZ1234567890';
Letter = Letter.split('');
function getauthkey() {
  let str = Letter[Math.floor(Math.random() * 36)] + Letter[Math.floor(Math.random() * 36)];
  return str + new Date().getTime();
}
let suiji = [1, 2, 3, 4].reduce((prev) => {
  return prev + Letter[Math.floor(Math.random() * 36)];
});

const Login = ({ location }) => {
  const { setInitialState } = useModel('@@initialState');
  const [auth_key, setauth_key] = useState();
  const [code, setcode] = useState();
  const [draw, setdraw] = useState();

  let { run } = useRequest(doFetch, {
    debounceWait: 300, //防抖
    manual: true,
    formatResult: (res) => res,
    onSuccess: (result) => {
      localStorage.setItem('TOKEN', result.jwt);
      if (!result.jwt) {
        dodraw();
        result.message && message.warn(result.message);
        return;
      }
      getFetch({ url: '/vehicle-api/user/info' }).then((res) => {
        setInitialState((s) => ({
          ...s,
          currentUser: res.data,
        }));
        history.push('/');
      });
    },
  });

  const handleSubmit = async (values) => {
    let val = encode_utf8_b64(values.password);
    val = encode_utf8_b64(val);
    val = encode_utf8_b64(val);
    if (code != draw) {
      message.warning('验证码错误！');
      dodraw();
      return;
    }
    run({
      url: '/vehicle-api/user_token',
      params: { ...values, password: val, auth_key: auth_key, code: code },
    });
  };

  useEffect(() => {
    let params = location.query;
    console.log(params);
    if (params?.token) {
      localStorage.setItem('TOKEN', params.token);
      history.push('/');
    }
  }, []);

  function dodraw() {
    let auth_key = getauthkey();
    setauth_key(auth_key);
    doFetch({ url: '/vehicle-api/auth_code', params: { auth_key } }).then((res) => {
      let code = window.atob(window.atob(window.atob(window.atob(window.atob(res?.data?.tpo)))));
      drawAuthCode('code', code ?? suiji);
      setdraw(code);
    });
  }

  useEffect(() => {
    drawAuthCode('code', suiji);
    dodraw();
  }, []);

  return (
    <div className={styles.container}>
      {location.pathname == '/user/login' && <MapBg />}

      <div className={styles.content}>
        <img
          alt="logo"
          src={require('@/assets/logo.png')}
          style={{ height: 44, width: 'auto', margin: '24px auto 22px auto' }}
        />
        <img alt="title" src={require('@/assets/title.png')} style={{ maxWidth: '100%' }} />
        <div className={`logbox ${styles.loginbox}`}>
          <div className={styles.border}>
            <LoginForm
              title={
                <span
                  style={{
                    color: '#fff',
                    fontSize: 16,
                    marginTop: -36,
                    display: 'block',
                    marginBottom: 16,
                    fontWeight: 'normal',
                  }}
                >
                  欢迎登录
                </span>
              }
              initialValues={{
                autoLogin: true,
              }}
              onFinish={async (values) => {
                await handleSubmit(values);
              }}
            >
              <>
                <ProFormText
                  name="name"
                  fieldProps={{
                    size: 'large',
                    prefix: <UserOutlined className={styles.prefixIcon} />,
                  }}
                  placeholder={'请输入用户名'}
                  rules={[
                    {
                      required: true,
                      message: '请输入用户名!',
                    },
                  ]}
                  style={{ background: '#135ea4' }}
                />
                <ProFormText.Password
                  name="password"
                  fieldProps={{
                    size: 'large',
                    prefix: <LockOutlined className={styles.prefixIcon} />,
                  }}
                  placeholder={'请输入密码'}
                  rules={[
                    {
                      required: true,
                      message: (
                        <FormattedMessage
                          id="pages.login.password.required"
                          defaultMessage="请输入密码！"
                        />
                      ),
                    },
                  ]}
                />
              </>

              <div className="center" style={{ marginBottom: 24 }}>
                <Input
                  style={{
                    backgroundColor: 'transparent',
                    color: '#92e4ff',
                    borderColor: '#0a81cc',
                    flex: 1,
                  }}
                  value={code}
                  onChange={(e) => {
                    setcode(e.target.value);
                  }}
                  size="large"
                  prefix={<SafetyOutlined className={styles.prefixIcon} />}
                  placeholder="请输入验证码"
                />
                <canvas
                  id="code"
                  style={{ width: '48%', marginLeft: '10px', height: 40 }}
                  onClick={() => {
                    dodraw();
                  }}
                />
              </div>
              <div>
                <ProFormCheckbox name="autoLogin">
                  <span style={{ color: '#fff' }}>自动登录</span>
                </ProFormCheckbox>
              </div>
            </LoginForm>
          </div>
        </div>

        <div style={{ flex: 1 }} />
      </div>
      <Footer
        style={{
          color: 'rgba(255,255,255,0.5)',
          background: 'transparent',
          position: 'absolute',
          bottom: 0,
          zIndex: 999,
          width: '100%',
        }}
      />
    </div>
  );
};

export default Login;
